import React from 'react'
import { connect } from 'react-redux'
import { Query } from 'react-apollo'
import getItemPage from 'graphql/getTaskItemPage.graphql'
import { projectLabelView as projectLabelViewDuck, global as globalDuck } from 'ducks'
import Content from './content'

const ItemPage = ({
  pid, user, state, actionReciveTaskItemPage, pageItems, limit, offset,
}) => {
  console.log(pid, user, state, actionReciveTaskItemPage, pageItems, limit, offset,)
  return (
    <Query
      query={getItemPage}
      variables={{
        projectId: pid,
        userId: user.id,
        state,
        limit,
        offset,
      }}
      fetchPolicy="network-only"
      onCompleted={(data) => {
        console.log('actionReciveTaskItemPage')
        actionReciveTaskItemPage(data.project_task_item)
      }}
    >
      {({ loading, error, data }) => {
        if (loading) return 'loading...'
        if (error) return `Error! ${error.message}`
        if (pageItems) return <Content pid={pid} />
        return null
      }}
    </Query>
  )
}

const mapStateToProps = state => ({
  offset: projectLabelViewDuck.selectors.pageInfo(state).offset,
  state: projectLabelViewDuck.selectors.pageInfo(state).state,
  limit: projectLabelViewDuck.selectors.pageInfo(state).limit,
  user: globalDuck.selectors.user(state),
  pageItems: projectLabelViewDuck.selectors.pageItemsInit(state),
})

const mapDispatchToProps = {
  actionReciveTaskItemPage: projectLabelViewDuck.creators.actionReciveTaskItemPage,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ItemPage)
